package com.peak.distribution.web.validator.method;

import java.util.Map;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Value;

import com.peak.distribution.web.validator.ValidateRuleMethod;
import com.peak.spring.boot.tools.Converts;
import com.peak.spring.boot.tools.Emptys;

public class Email implements ValidateRuleMethod {
	
	@Value("${validate.rule.email}")
	private String errorMessage;
	
	private String pattern = "[\\w\\-\u4e00-\u9fa5]{1,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";

	@Override
	public boolean execute(Object value) {
		if (Emptys.isEmpty(value)) {// 空的数据不校验，使用Require类校验
			return true;
		}
		Pattern p = Pattern.compile(pattern);
		return p.matcher(Converts.toString(value)).matches();
	}

	@Override
	public String getErrorMessageTemplate() {
		return Emptys.isEmpty(this.errorMessage) ? "{0}的格式不正确，请输入符合邮箱标准的格式，如：example@163.com" : this.errorMessage;
	}

	@Override
	public void setParams(Map<String, Object> param) {
		Object pattern = param.get("pattern");
		if (Emptys.isNotEmpty(pattern)) {
			this.pattern = Converts.toString(pattern);
		}
	}
}
